import React, { useEffect, useState } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  ScrollView,
  TouchableOpacity,
  Modal,
  ActivityIndicator
} from "react-native";
import { Image } from "expo-image";
import { SafeAreaView } from "react-native-safe-area-context";
import { useLocalSearchParams, useRouter, Stack } from "expo-router";
import { 
  ArrowLeft, 
  Heart, 
  Share, 
  Bookmark, 
  Volume2,
  Nfc,
  CheckCircle,
  XCircle
} from "lucide-react-native";
import { colors } from "@/constants/colors";
import { AudioPlayer } from "@/components/AudioPlayer";
import { useContentStore } from "@/store/content-store";
import { useNFCStore } from "@/store/nfc-store";
import { Platform } from "react-native";

export default function ContentDetailScreen() {
  const { id } = useLocalSearchParams();
  const router = useRouter();
  const { contents, favorites, toggleFavorite } = useContentStore();
  const { writeTag, isScanning } = useNFCStore();
  const [showNfcModal, setShowNfcModal] = useState(false);
  const [nfcWriteSuccess, setNfcWriteSuccess] = useState<boolean | null>(null);
  
  // Find the content by ID
  const content = contents.find(item => item.id === id);
  
  // Check if content is favorited
  const isFavorite = favorites.includes(content?.id || "");
  
  useEffect(() => {
    if (!content) {
      // Content not found, go back
      router.back();
    }
  }, [content, router]);
  
  if (!content) {
    return null;
  }
  
  // Handle NFC write
  const handleNfcWrite = async () => {
    setShowNfcModal(true);
    setNfcWriteSuccess(null);
    
    try {
      const success = await writeTag(content.id);
      setNfcWriteSuccess(success);
      
      // Close modal after success
      if (success) {
        setTimeout(() => {
          setShowNfcModal(false);
          setNfcWriteSuccess(null);
        }, 2000);
      }
    } catch (error) {
      console.error("NFC write error:", error);
      setNfcWriteSuccess(false);
    }
  };
  
  // Handle share
  const handleShare = () => {
    // In a real app, we would use expo-sharing to share the content
    console.log("Sharing content:", content.title);
  };
  
  // Handle speak
  const handleSpeak = () => {
    // In a real app, we would use expo-speech to speak the text
    console.log("Speaking:", content.english);
  };
  
  // Close NFC modal
  const closeNfcModal = () => {
    setShowNfcModal(false);
    setNfcWriteSuccess(null);
  };
  
  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <Stack.Screen 
        options={{
          title: content.title,
          headerShown: true,
          headerLeft: () => (
            <TouchableOpacity onPress={() => router.back()}>
              <ArrowLeft size={24} color={colors.text.primary} />
            </TouchableOpacity>
          ),
          headerRight: () => (
            <View style={styles.headerActions}>
              <TouchableOpacity 
                style={styles.headerAction}
                onPress={() => toggleFavorite(content.id)}
              >
                <Heart 
                  size={24} 
                  color={isFavorite ? colors.accent : colors.text.primary}
                  fill={isFavorite ? colors.accent : "none"}
                />
              </TouchableOpacity>
              <TouchableOpacity 
                style={styles.headerAction}
                onPress={handleShare}
              >
                <Share size={24} color={colors.text.primary} />
              </TouchableOpacity>
            </View>
          ),
        }}
      />
      
      <ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContent}>
        {/* Content image */}
        <View style={styles.imageContainer}>
          {content.imageUrl ? (
            <Image
              source={{ uri: content.imageUrl }}
              style={styles.image}
              contentFit="cover"
            />
          ) : (
            <View style={[styles.image, styles.placeholderImage]} />
          )}
          
          <View style={styles.badgeContainer}>
            <View style={styles.typeBadge}>
              <Text style={styles.badgeText}>{content.type}</Text>
            </View>
            <View 
              style={[
                styles.difficultyBadge,
                { 
                  backgroundColor: 
                    content.difficulty === "beginner" ? colors.success :
                    content.difficulty === "intermediate" ? colors.secondary :
                    colors.accent
                }
              ]}
            >
              <Text style={styles.badgeText}>{content.difficulty}</Text>
            </View>
          </View>
        </View>
        
        {/* Content details */}
        <View style={styles.contentContainer}>
          <Text style={styles.title}>{content.title}</Text>
          
          <View style={styles.textContainer}>
            <View style={styles.textHeader}>
              <Text style={styles.textLabel}>English</Text>
              <TouchableOpacity onPress={handleSpeak}>
                <Volume2 size={20} color={colors.primary} />
              </TouchableOpacity>
            </View>
            <Text style={styles.englishText}>{content.english}</Text>
          </View>
          
          <View style={styles.textContainer}>
            <Text style={styles.textLabel}>Chinese</Text>
            <Text style={styles.chineseText}>{content.chinese}</Text>
          </View>
          
          {/* Tags */}
          <View style={styles.tagsContainer}>
            <Text style={styles.tagsLabel}>Tags:</Text>
            <View style={styles.tagsList}>
              {content.tags.map((tag, index) => (
                <View key={index} style={styles.tag}>
                  <Text style={styles.tagText}>{tag}</Text>
                </View>
              ))}
            </View>
          </View>
          
          {/* Audio player */}
          <AudioPlayer
            title={content.title}
            audioUrl={content.audioUrl}
          />
          
          {/* NFC button - only show on mobile */}
          {Platform.OS !== "web" && (
            <TouchableOpacity 
              style={styles.nfcButton}
              onPress={handleNfcWrite}
            >
              <Nfc size={24} color={colors.text.inverse} />
              <Text style={styles.nfcButtonText}>Write to NFC Tag</Text>
            </TouchableOpacity>
          )}
        </View>
      </ScrollView>
      
      {/* NFC Modal */}
      <Modal
        visible={showNfcModal}
        transparent={true}
        animationType="fade"
        onRequestClose={closeNfcModal}
      >
        <View style={styles.nfcModalOverlay}>
          <View style={styles.nfcModal}>
            {isScanning && nfcWriteSuccess === null && (
              <>
                <ActivityIndicator size="large" color={colors.primary} style={styles.nfcModalIcon} />
                <Text style={styles.nfcModalTitle}>Tap NFC Tag</Text>
                <Text style={styles.nfcModalText}>
                  Hold your device near the NFC tag to write content
                </Text>
                <TouchableOpacity 
                  style={styles.nfcModalCancelButton}
                  onPress={closeNfcModal}
                >
                  <Text style={styles.nfcModalCancelText}>Cancel</Text>
                </TouchableOpacity>
              </>
            )}
            
            {nfcWriteSuccess === true && (
              <>
                <CheckCircle size={60} color={colors.success} style={styles.nfcModalIcon} />
                <Text style={styles.nfcModalTitle}>Success!</Text>
                <Text style={styles.nfcModalText}>
                  Content successfully written to NFC tag
                </Text>
              </>
            )}
            
            {nfcWriteSuccess === false && (
              <>
                <XCircle size={60} color={colors.accent} style={styles.nfcModalIcon} />
                <Text style={styles.nfcModalTitle}>Failed</Text>
                <Text style={styles.nfcModalText}>
                  Failed to write content to NFC tag. Please try again.
                </Text>
                <TouchableOpacity 
                  style={styles.nfcModalRetryButton}
                  onPress={handleNfcWrite}
                >
                  <Text style={styles.nfcModalRetryText}>Retry</Text>
                </TouchableOpacity>
                <TouchableOpacity 
                  style={styles.nfcModalCancelButton}
                  onPress={closeNfcModal}
                >
                  <Text style={styles.nfcModalCancelText}>Cancel</Text>
                </TouchableOpacity>
              </>
            )}
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingBottom: 24,
  },
  headerActions: {
    flexDirection: "row",
  },
  headerAction: {
    marginLeft: 16,
  },
  imageContainer: {
    position: "relative",
  },
  image: {
    width: "100%",
    height: 250,
  },
  placeholderImage: {
    backgroundColor: colors.card,
  },
  badgeContainer: {
    position: "absolute",
    top: 16,
    left: 16,
    flexDirection: "row",
  },
  typeBadge: {
    backgroundColor: "rgba(0, 0, 0, 0.6)",
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 4,
    marginRight: 8,
  },
  difficultyBadge: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 4,
  },
  badgeText: {
    color: colors.text.inverse,
    fontSize: 12,
    fontWeight: "600",
    textTransform: "uppercase",
  },
  contentContainer: {
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 16,
  },
  textContainer: {
    marginBottom: 16,
  },
  textHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 8,
  },
  textLabel: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.secondary,
    marginBottom: 8,
  },
  englishText: {
    fontSize: 18,
    color: colors.text.primary,
    lineHeight: 28,
  },
  chineseText: {
    fontSize: 18,
    color: colors.text.primary,
    lineHeight: 28,
  },
  tagsContainer: {
    marginBottom: 24,
  },
  tagsLabel: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.secondary,
    marginBottom: 8,
  },
  tagsList: {
    flexDirection: "row",
    flexWrap: "wrap",
  },
  tag: {
    backgroundColor: colors.primary + "20",
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
    marginRight: 8,
    marginBottom: 8,
  },
  tagText: {
    fontSize: 14,
    color: colors.primary,
  },
  nfcButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: colors.primary,
    borderRadius: 8,
    paddingVertical: 12,
    marginTop: 16,
  },
  nfcButtonText: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.inverse,
    marginLeft: 8,
  },
  nfcModalOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: "rgba(0, 0, 0, 0.7)",
    justifyContent: "center",
    alignItems: "center",
    zIndex: 1000,
  },
  nfcModal: {
    backgroundColor: colors.background,
    borderRadius: 16,
    padding: 24,
    alignItems: "center",
    width: "80%",
  },
  nfcModalIcon: {
    marginBottom: 16,
  },
  nfcModalTitle: {
    fontSize: 20,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 8,
  },
  nfcModalText: {
    fontSize: 16,
    color: colors.text.secondary,
    textAlign: "center",
    lineHeight: 24,
    marginBottom: 16,
  },
  nfcModalRetryButton: {
    backgroundColor: colors.primary,
    borderRadius: 8,
    paddingVertical: 12,
    paddingHorizontal: 24,
    marginBottom: 12,
    width: "100%",
    alignItems: "center",
  },
  nfcModalRetryText: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.inverse,
  },
  nfcModalCancelButton: {
    paddingVertical: 12,
    paddingHorizontal: 24,
    width: "100%",
    alignItems: "center",
  },
  nfcModalCancelText: {
    fontSize: 16,
    color: colors.text.secondary,
  },
});